use std::time::Duration;
use rocket::futures::executor::block_on;
use sea_orm::{ConnectOptions, Database, DatabaseConnection};
use crate::SelfConfig;

static mut db:Option<DatabaseConnection> = None;

//单例对象
pub fn get_db() -> &'static DatabaseConnection{
	unsafe {
		match &db {
			None => {
				let config_mysql = &SelfConfig::get_self_config().mysql;
				let mut opt =
					ConnectOptions::new(
						format!("mysql://{user}:{password}@{url}"
						        , user = config_mysql.user
						        , password = config_mysql.password
						        , url = config_mysql.url));
				opt.max_connections(100)
					.min_connections(5)
					.connect_timeout(Duration::from_secs(8))
					.idle_timeout(Duration::from_secs(8))
					.max_lifetime(Duration::from_secs(8))
					.sqlx_logging(true);
				db = Some(block_on(Database::connect(opt)).expect("数据库连接错误"));
				if let Some(v) = &db {
					v
				} else {
					todo!("我永远不会被执行")
				}
			}
			Some(v) => v
		}
	}
}
